import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { getScrollTop, getWindowHeight, getScrollHeight } from '@/utils/h5'

import { View, Text, Image, ScrollView } from '@tarojs/components'

import styles from './index.scss';

export interface ListTemplateProps {
  pageSize?: number;
  preload?: boolean; //是否自动加载，参数是异步获取需设置false
  fetchFn: Function; //获取数据的方法
  initialListSize?: number; //首页加载的条数，暂时没有实现，用pageSize去控制
  noText?: string;
  useBodyScroll: true,
  noImg?: any;
  children: Function
}
export interface ListTemplateState {
  dataSource: any;
  loading: boolean;
  end: boolean;
  empty: boolean;
  height: number
}
class Index extends Component<ListTemplateProps, ListTemplateState> {
  lv: any;
  contaienr: any;
  _data: Array<object> = [];
  page: number = 1;
  total: number = 0;
  static defaultProps = {
    pageSize: 10,
    preload: true,
    useBodyScroll: true
  };
  constructor(props) {
    super(props);
    this.state = {
      height: 300,
      dataSource: [],
      loading: false,
      empty: false,
      end: false,
    };
  }
  //模拟数据
  createData = (page, pageSize) => {
    let listData = [
      {
        "name": "!"
      },
      {
        "name": "Hello"
      },
      {
        "name": "Mock.js"
      },
      {
        "name": "!"
      },
      {
        "name": "Hello"
      },
      {
        "name": "Mock.js"
      },
      {
        "name": "!"
      },
      {
        "name": "Hello"
      },
      {
        "name": "Mock.js"
      },
      {
        "name": "!"
      },
      {
        "name": "Hello"
      },
      {
        "name": "Mock.js"
      },
      {
        "name": "!"
      },
      {
        "name": "Hello"
      },
      {
        "name": "Mock.js"
      },
      {
        "name": "!"
      },
      {
        "name": "Hello"
      },
      {
        "name": "Mock.js"
      },
      {
        "name": "!"
      }
    ]
    // const data={
    //     list:listData.slice(pageSize*page,(pageSize*page+pageSize)
    // }
    console.log(page, pageSize)
    page = page - 1
    const arr = listData.slice(pageSize * page, (pageSize * page + pageSize));
    console.log(arr, 'aaaaaa', pageSize * page, (pageSize * page + pageSize))
    const data = {
      list: arr,
      pageSize,
      page,
      totalPage: 4
    }
    return { data }
  }
  componentDidMount() {
    const { preload, useBodyScroll } = this.props;
    const $this = this
    preload && this.initLoad();
    if (process.env.TARO_ENV === 'h5' && useBodyScroll) {
      window.onscroll = function () {
        console.log('sss')
        if (getScrollTop() + getWindowHeight() == getScrollHeight()) {
          $this.getData()
          console.log("已经到最底部了！!");
          // 这里可以调用接口请求数据了，滑动到底部自动加载数据
        }
      }
    } else {
      setTimeout(() => {
        const query = Taro.createSelectorQuery()
        query.select('.listTemplateContainer').boundingClientRect()
        query.exec(function (res) {
          if (res[0]) {
            Taro.getSystemInfo().then((data) => {
              $this.setState({
                height: data.windowHeight - res[0].top
              })
            })
          }              // #the-id节点的上边界坐标
        })
      }, 100)
    }
  }
  initLoad = () => {
    this.page = 1;
    this.total = 0;
    this.setState({
      end: false,
      empty: false,
      dataSource: [],
    });
    this.getData();
  };
  getData = () => {
    const { dataSource, loading } = this.state;
    if (this.total === this.page || loading) {
      //如果是最后一页或者正在加载
      return;
    }
    const { fetchFn, pageSize } = this.props;
    this.setState({ loading: true });
    console.log('aaaaaaa')
    // fetchFn({ pageSize, page: this.page }).then(data => {
    //   data=data.data
    //   this.total = data.totalPage;
    //   console.log(data,'asdasd')
    //   if (this.page===1) {
    //     this._data = [...data.list];
    //   } else {
    //     this._data = [...this._data, ...data.list];
    //   }
    //   this.page += 1;
    //   this.setState({
    //     dataSource: this._data,
    //     loading: false,
    //     end: this.total === this.page,
    //     empty: this.page === 1 && data.list.length === 0,
    //   });
    // });\
    let data = this.createData(this.page, pageSize)
    data = data.data
    this.total = data.totalPage;
    console.log(data, 'asdasd')
    if (this.page === 1) {
      this._data = [...data.list];
    } else {
      this._data = [...this._data, ...data.list];
    }
    this.page += 1;
    this.setState({
      dataSource: this._data,
      loading: false,
      end: this.total === this.page,
      empty: this.page === 1 && data.list.length === 0,
    });
  };
  render() {
    const { dataSource, loading, end, empty, height } = this.state;
    console.log(dataSource)
    const { children, noText, noImg, useBodyScroll } = this.props;
    return (
      <ScrollView
        scrollY
        refresherEnabled
        className='listTemplateContainer'
        style={{ height: (useBodyScroll && process.env.TARO_ENV === 'h5') ? 'auto' : `${height}px` }}
        onScrollToLower={this.getData}
        ref={ref => {
          this.contaienr = ref;
        }}
      >
        {dataSource.map((rowData, index) => {
          console.log(rowData, 'aa')
          return children(rowData, index)
        })}
        {empty && (
          <View className={styles.empty}>
            <Image
              className={styles.noImg}
            // src={noImg ? noImg : require('../../assets/img/no_data.png')}
            />
            <View className={styles.noText}>
              <Text>{noText ? noText : '没有数据...'}</Text>
            </View>
          </View>
        )}
        {loading && this.page === 1 && (
          <View className={styles.firstLoading}>
            <Image />
          </View>
        )}
        {empty ? (
          ''
        ) : end ? (
          '没有更多啦～'
        ) : loading ? (
          this.page != 1 ? (
            <Image
              className={styles.bottomLoading}
              // src={require('../../assets/img/bottom_loading.gif')}
              alt=''
            />
          ) : (
              ''
            )
        ) : (
                '上拉加载'
              )}
      </ScrollView>
    );
  }
}

export default Index



